package org.tbjd.client.listeners;

import java.util.HashMap;
import java.util.Map;

import org.tbjd.client.constants.NotificationsConstants;
import org.tbjd.client.exceptions.TBJDException;
import org.tbjd.client.exceptions.NoUpperDecisionmakerFoundException;
import org.tbjd.client.helpers.ProjectStatusFilterHelper;
import org.tbjd.client.interfaces.Decisionmaker;

import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class SearchBoxKeyboardListener extends KeyboardListenerAdapter implements Decisionmaker {
	
	private Widget sender = null;

	public void onKeyUp(Widget sender, char keyCode, int arg2) {
		this.sender = sender;
		if (keyCode == KEY_ESCAPE || ((TextBox)sender).getText().equalsIgnoreCase("")) {
			((TextBox) sender).setText("");
			ProjectStatusFilterHelper.getInstance().setSearchCriteria("");
			ProjectStatusFilterHelper.getInstance().setSearch(Boolean.FALSE);
		}

		ProjectStatusFilterHelper.getInstance().setSearchCriteria(((TextBox) sender).getText());
		ProjectStatusFilterHelper.getInstance().setSearch(Boolean.TRUE);
		Map<Integer, Object> map = new HashMap<Integer, Object>();
		map.put(NotificationsConstants.FETCH_PROJECTS, ProjectStatusFilterHelper.getInstance());
		decide(map);
	}

	public void decide(Object action) {
		System.out.println("SearchBoxKeyboardListener.decide(" + action + ")");

		try {
			delegate(action);
		} catch (NoUpperDecisionmakerFoundException e) {
			e.toString();
		}
	}

	public void delegate(Object action) throws NoUpperDecisionmakerFoundException {
		System.out.println("SearchBoxKeyboardListener.delegate(" + sender + ")");

		// passes info to the first responsible
		Widget parent = ((Widget) sender).getParent();
		while (parent != null && parent instanceof Decisionmaker == false) {
			parent = ((Widget) parent).getParent();
		}
		if (parent != null) {
			try {
				((Decisionmaker) parent).decide(action);
			} catch (TBJDException e) {
				e.printStackTrace();
			}
		} else {
			throw new NoUpperDecisionmakerFoundException();
		}
	}

	public void handle(Object action) {
	}

}
